package com.foryou.system.modules.wx.controller;

import com.foryou.system.common.bootstrap.PageUtils;
import com.foryou.system.common.bootstrap.Query;
import com.foryou.system.common.exception.RollbackException;
import com.foryou.system.common.utils.FileUtil;
import com.foryou.system.common.utils.R;
import com.foryou.system.modules.wx.service.UserBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * Created by Lee.
 */
@RestController
@RequestMapping("/wx/user/back")
public class UserBackController {

    @Autowired
    private UserBackService userBackService;

    @Value("${web.upload-path}")
    private String path;

    @Value("${web.url}")
    private String url;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        int total = userBackService.queryTotal(query);
        return new PageUtils(userBackService.queryList(query), total);
    }

    @RequestMapping("/remove")
    public R remove(@RequestBody Long[] ids) {
        userBackService.remove(ids);
        return R.ok();
    }

    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        userBackService.delete(ids);
        return R.ok();
    }

    @RequestMapping("/update")
    public R delete(@RequestBody Map<String,Object> params) {
        userBackService.update(params);
        return R.ok();
    }

    @RequestMapping("/upload")
    public R upload(@RequestParam MultipartFile[] uploadFile) {
        for (MultipartFile file : uploadFile) {
            if (file.isEmpty()) {
                throw new RollbackException("文件未上传");
            }
        }

        for (MultipartFile file : uploadFile) {
            String saveName  = FileUtil.RenameToUUID(file.getOriginalFilename());
            try {
                FileUtil.uploadFile(file.getBytes(), path, saveName);
                userBackService.save(url.concat(saveName));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return R.ok();
    }

}
